package servlet;

import dao.EquipmentDaoImpl;
import utils.string.session.SessionStringUtil;
import vo.Equipment;
import vo.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

public class AddEquipmentServlet extends HttpServlet {
    //该Servlet主要是解决设备添加的问题
    EquipmentDaoImpl equipmentDao = new EquipmentDaoImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //编码设计
        req.setCharacterEncoding("UTF-8");
        String addEquipmentName =  req.getParameter("addEquipmentName");
        int addEquipmentNum = Integer.parseInt(req.getParameter("addEquipmentNum"));
        Equipment equipment = new Equipment();
        equipment.setEquip_name(addEquipmentName);
        equipment.setEquip_num(addEquipmentNum);
        equipmentDao.insertEquipment(equipment);
        HashMap equipments = equipmentDao.selectAll();
        //数据传递
        req.getSession().setAttribute(SessionStringUtil.ALL_UNUSED_EQUIPMENTS,equipments);
        jumpToJsp(req,resp);
    }

    private void jumpToJsp(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        User user = (User) req.getSession().getAttribute(SessionStringUtil.USER);
        if(user.getAuth_id() == 1){
            resp.sendRedirect("/equipmentManager_war_explode/manageAllEquipments.jsp");//跳转到管理者的Fix界面
        }else{
            resp.sendRedirect("/equipmentManager_war_explode/manageUserEquipments.jsp");//普通用户的界面
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //数据传递
        HashMap equipments = equipmentDao.selectAll();
        req.getSession().setAttribute(SessionStringUtil.ALL_UNUSED_EQUIPMENTS,equipments);
        jumpToJsp(req,resp);
    }
}
